<template>
  <div class="home">
    <el-row type="flex" class="row-bg" justify="center">
      <el-col :xl="12" :lg="14">
        <el-form ref="ruleForm" class="ruleForm" :rules="rules" :model="formData" label-width="120px">
          <el-form-item label="产品名称" prop="appName">
            <el-input v-model="formData.appName" />
          </el-form-item>

          <el-form-item label="产品描述" prop="functionDesc">
            <el-input
              v-model="formData.functionDesc"
              type="textarea"
              :maxlength="200"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 4 }"
              placeholder="请输入你的应用描述"
            />
          </el-form-item>

          <el-form-item v-loading="serviceLoading" label="开通服务" prop="services">
            <div v-for="(service, serviceIndex) in services" :key="serviceIndex" class="service-content">
              <div class="service-header">
                <div class="title">{{ service.serviceCategory }}</div>
                <div class="subtitle">{{ service.serviceName }}</div>
              </div>

              <div v-for="(route, routeIndex) in service.routes" :key="routeIndex" class="route-section">
                <el-checkbox-group v-model="formData.services" @change="handleServiceChange">
                  <el-checkbox :label="route.nodeCode" class="check-box">
                    {{ route.nodeName }}
                  </el-checkbox>
                </el-checkbox-group>

                <div v-if="formData.services.includes(route.nodeCode)" class="children-section">
                  <div v-for="(child, childIndex) in route.children" :key="childIndex" class="child-item">
                    <span class="child-name">{{ child.nodeName }}</span>
                    <el-form-item
                      :prop="`serviceWeights.${service.serviceId}.${route.nodeCode}.${child.nodeCode}`"
                      :rules="rulesNumber"
                    >
                      <el-input
                        v-model.number="formData.serviceWeights[service.serviceId][route.nodeCode][child.nodeCode]"
                        class="weight-input"
                        placeholder="请输入"
                        type="number"
                        min="0"
                        max="100"
                      />
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="form-actions">
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>

export default {
  name: 'HomePage',

  data() {
    return {
      serviceLoading: false,
      services: [],
      formData: {
        appName: '',
        functionDesc: '',
        services: [],
        serviceWeights: {}
      },
      rules: {
        appName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        functionDesc: [
          { required: true, message: '请输入产品描述', trigger: 'blur' }
        ],
        services: [
          { required: true, message: '请至少选择一个服务', trigger: 'change' }
        ]
      },
      rulesNumber: [
        { required: true, message: '请输入', trigger: 'blur' }
      ]
    }
  },

  created() {
    this.fetchServices()
  },

  methods: {
    async fetchServices() {
      try {
        this.serviceLoading = true
        // mock
        const response =
        [
          {
            serviceId: 1,
            serviceCategory: '语音合成',
            serviceName: '短文本流合成',
            hidden: true,
            routes: [
              {
                nodeName: '小布',
                hidden: false,
                nodeCode: 'xiaobu_young',
                nodeValue: 67,
                children: [
                  {
                    nodeName: '自研2',
                    hidden: false,
                    nodeCode: 'BYS2',
                    nodeValue: 91
                  },
                  {
                    nodeName: '讯飞2',
                    hidden: false,
                    nodeCode: 'XF2',
                    nodeValue: 38
                  },
                  {
                    nodeName: '讯飞2',
                    hidden: false,
                    nodeCode: 'XF232',
                    nodeValue: 38
                  },
                  {
                    nodeName: '讯飞2',
                    hidden: false,
                    nodeCode: 'XF11',
                    nodeValue: 38
                  },
                  {
                    nodeName: '讯飞2',
                    hidden: false,
                    nodeCode: 'XF23',
                    nodeValue: 38
                  }
                ]
              }
            ]
          }
        ]

        this.services = response
        this.init(response)
      } catch (error) {
        this.$message.error('获取服务列表失败')
      } finally {
        this.serviceLoading = false
      }
    },
    init(services) {
      const weights = {}
      services.forEach(service => {
        weights[service.serviceId] = {}
        service.routes.forEach(route => {
          weights[service.serviceId][route.nodeCode] = {}
          route.children.forEach(child => {
            weights[service.serviceId][route.nodeCode][child.nodeCode] = child.nodeValue
          })
        })
      })
      this.$set(this.formData, 'serviceWeights', weights)
    },

    handleServiceChange(values) {
      console.log('监听是否有数据可以查看value', values)
    },

    // 数据处理map
    formatSubmitData() {
      const formattedServices = this.services.map(service => {
        return {
          serviceId: service.serviceId,
          serviceCategory: service.serviceCategory,
          serviceName: service.serviceName,
          hidden: service.hidden,
          routes: service.routes.map(route => {
            if (this.formData.services.includes(route.nodeCode)) {
              return {
                nodeName: route.nodeName,
                hidden: route.hidden,
                nodeCode: route.nodeCode,
                nodeValue: route.nodeValue,
                children: route.children.map(child => ({
                  nodeName: child.nodeName,
                  hidden: child.hidden,
                  nodeCode: child.nodeCode,
                  nodeValue: this.formData.serviceWeights[service.serviceId][route.nodeCode][child.nodeCode]
                }))
              }
            }
            return null
          }).filter(route => route !== null)
        }
      })

      return {
        appName: this.formData.appName,
        functionDesc: this.formData.functionDesc,
        services: formattedServices
      }
    },

    async onSubmit() {
      try {
        await this.$refs.ruleForm.validate()

        const submitData = this.formatSubmitData()

        console.log(submitData, 'submitData')
      } catch (error) {
        console.error('Submit error:', error)
        this.$message.error('提交失败')
      }
    }
  }
}
</script>

<style scoped>
.home {
  padding: 20px;
}

</style>
